package edu.neu.cloud_factory.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import edu.neu.cloud_factory.dao.BidMapper;
import edu.neu.cloud_factory.dao.ProductMapper;
import edu.neu.cloud_factory.dao.UserMapper;
import edu.neu.cloud_factory.entity.po.*;
import edu.neu.cloud_factory.dao.OrderMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.neu.cloud_factory.entity.vo.OrderVo;
import edu.neu.cloud_factory.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.apache.commons.collections4.ListUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author halozhy
 * @since 2021-07-15
 */
@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IService<Order> {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    BidMapper bidMapper;

    public boolean isHaveUnfinishedByUserId(int uId) {
        User u = userMapper.selectById(uId);
        if (u.getUType().equals("经销商")){
            // 如果是经销商。查询用户下是否有未完成的订单
            Map<String, Object> colMap = new HashMap<>();
            colMap.put("o_user_id", uId);
            List<Order> orderList = orderMapper.selectByMap(colMap);
            for (Order o : orderList) {
                if (!o.getOState().equals("已结束")) {
                    return true; //  只要发现了不是已经结束的订单，就返回true
                }
            }
        }
        else if (u.getUType().equals("云工厂管理员")){
            // 如果是云工厂管理员，则是需要判断中标的情况，来判断是否有未完成的订单
            // 1. 查到工厂id
            // 2. 通过工厂id查到所有的相关bid
            Map<String ,Object> colMap = new HashMap<>();
            colMap.put("b_factory_id", u.getUFactoryId());
            List<Bid> bidList = bidMapper.selectByMap(colMap);
            // 3. for里，对每个bid关联到order进行状态检查
            for (Bid b :
                    bidList) {
                Order order = orderMapper.selectById(b.getBOrderId());
                if (!order.getOState().equals("已结束")) {
                    return true; //  只要发现了不是已经结束的订单，就返回true
                }
            }
        }
        return false;
    }

    public List<Order> selectOrderByProductId(Long pId) {
        Map<String, Object> colMap = new HashMap<>();
        colMap.put("o_product_id", pId);
        return orderMapper.selectByMap(colMap);
    }


    public JSONObject listOrderDealer(Integer page, Integer limit, long userId, String id, String receiver_name, String product_name) {
        User u = userMapper.selectById(userId);
        if (u == null || !u.getUType().equals("经销商")) {
            return null;
        }
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        if (id != null && !id.isEmpty()) {
            queryWrapper.like("o_id", id);
        }
        if (receiver_name != null && !receiver_name.isEmpty()) {
            queryWrapper.like("o_receiver_name", receiver_name);
        }
        if (product_name != null && !product_name.isEmpty()) {
            queryWrapper.like("p_name", product_name);
        }
        queryWrapper.eq("o_user_id", userId);

        List<Order> orderList = orderMapper.listJoinProduct(queryWrapper);

        List<Product> productList = productMapper.selectList(null);
        Map<Long, Product> productMap = new HashMap<>();
        productList.forEach(product -> {
            productMap.put(product.getPId(), product);
        });

        List<User> userList = userMapper.selectList(null);
        Map<Long, User> userMap = new HashMap<>();
        userList.forEach(user -> {
            userMap.put(user.getUId(), user);
        });

        List<OrderVo> orderVoList = new ArrayList<>();
        for (int i = 0; i < orderList.size(); i++) {
            Order order = orderList.get(i);
            OrderVo orderVo = new OrderVo();
            orderVo.setId(order.getOId());
            orderVo.setState(order.getOState());
            orderVo.setNum(order.getONum());
            orderVo.setReceiver_name(order.getOReceiverName());
            orderVo.setReceiver_tel(order.getOReceiverTel());
            orderVo.setReceiver_addr(order.getOReceiverAddr());
            orderVo.setDeliver_date(order.getODeliverDate());
            orderVo.setBid_end_date(order.getOBidEndDate());

            orderVo.setProduct_id(order.getOProductId());
            orderVo.setProduct_name(productMap.get(order.getOProductId()).getPName());

            orderVo.setUser_id(order.getOUserId());
            orderVo.setUser_true_name(userMap.get(order.getOUserId()).getUName());

            orderVoList.add(orderVo);
        }
        JSONObject result = new JSONObject();
        // 不知为何分页又出问题了，手动分页算了
        result.put("count", orderVoList.size()); // 先拿到总数
        result.put("data", Utils.pageByMe(orderVoList, page, limit));
        return result;
    }

    public JSONObject listOrderFacCanBid(Integer page, Integer limit, long userId, String id, String receiver_name, String product_name) {
        // 列出所有可以被竞标的订单，需要注意，把自己已经竞过的要排除
        User u = userMapper.selectById(userId);
        if (u == null || !u.getUType().equals("云工厂管理员")) {
            return null;
        }
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        if (id != null && !id.isEmpty()) {
            queryWrapper.like("o_id", id);
        }
        if (receiver_name != null && !receiver_name.isEmpty()) {
            queryWrapper.like("o_receiver_name", receiver_name);
        }
        if (product_name != null && !product_name.isEmpty()) {
            queryWrapper.like("p_name", product_name);
        }
        queryWrapper.eq("o_state", "已发布");

        // 不知为何分页又出问题了，手动分页算了
        List<Order> orderList = orderMapper.listJoinProduct(queryWrapper);


        List<Product> productList = productMapper.selectList(null);
        Map<Long, Product> productMap = new HashMap<>();
        productList.forEach(product -> {
            productMap.put(product.getPId(), product);
        });

        List<User> userList = userMapper.selectList(null);
        Map<Long, User> userMap = new HashMap<>();
        userList.forEach(user -> {
            userMap.put(user.getUId(), user);
        });

        Map<String, Object> colMap = new HashMap<>();
        colMap.put("b_factory_id", u.getUFactoryId());
        colMap.put("b_state", "已投标");
        List<Bid> myBids = bidMapper.selectByMap(colMap); // 自己正在竞标中的竞标信息

        List<OrderVo> orderVoList = new ArrayList<>();
        for (int i = 0; i < orderList.size(); i++) {
            Order order = orderList.get(i);
            // 先检查这个order是不是已经投过了
            boolean flag = false;
            for (Bid b : myBids) {
                if (order.getOId().equals(b.getBOrderId())) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                continue; // 投过标了，不在此返回值中显示
            }
            OrderVo orderVo = new OrderVo();
            orderVo.setId(order.getOId());
            orderVo.setState(order.getOState());
            orderVo.setNum(order.getONum());
            orderVo.setReceiver_name(order.getOReceiverName());
            orderVo.setReceiver_tel(order.getOReceiverTel());
            orderVo.setReceiver_addr(order.getOReceiverAddr());
            orderVo.setDeliver_date(order.getODeliverDate());
            orderVo.setBid_end_date(order.getOBidEndDate());

            orderVo.setProduct_id(order.getOProductId());
            orderVo.setProduct_name(productMap.get(order.getOProductId()).getPName());

            orderVo.setUser_id(order.getOUserId());
            orderVo.setUser_true_name(userMap.get(order.getOUserId()).getUName());

            orderVoList.add(orderVo);
        }

        JSONObject result = new JSONObject();
        result.put("count", orderVoList.size()); // 先拿到总数
        result.put("data", Utils.pageByMe(orderVoList, page, limit));
        return result;
    }

    public JSONObject listOrderFacAlreadyBid(Integer page, Integer limit, long userId, String id, String receiver_name, String product_name) {
        User u = userMapper.selectById(userId);
        if (u == null || !u.getUType().equals("云工厂管理员")) {
            return null;
        }
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        if (id != null && !id.isEmpty()) {
            queryWrapper.like("o_id", id);
        }
        if (receiver_name != null && !receiver_name.isEmpty()) {
            queryWrapper.like("o_receiver_name", receiver_name);
        }
        if (product_name != null && !product_name.isEmpty()) {
            queryWrapper.like("p_name", product_name);
        }
        queryWrapper.eq("b_factory_id", u.getUFactoryId());
        List<Order> orderList = orderMapper.listJoinProductJoinBid(queryWrapper);

        List<Product> productList = productMapper.selectList(null);
        Map<Long, Product> productMap = new HashMap<>();
        productList.forEach(product -> {
            productMap.put(product.getPId(), product);
        });

        List<User> userList = userMapper.selectList(null);
        Map<Long, User> userMap = new HashMap<>();
        userList.forEach(user -> {
            userMap.put(user.getUId(), user);
        });

        List<OrderVo> orderVoList = new ArrayList<>();
        for (int i = 0; i < orderList.size(); i++) {
            Order order = orderList.get(i);
            OrderVo orderVo = new OrderVo();
            orderVo.setId(order.getOId());
            // 在订单排产页面，如果订单的状态是已发布，且和其关联的自己的竞标是已投标，那么Vo里面要显示已投标，这样比较符合逻辑习惯
            // 如果订单关联的自己的竞标是已中标，那么Vo里面要显示已中标
            // 如果订单关联的自己的竞标是未中标，那么Vo里面要显示未中标
            Map<String,Object> colMap = new HashMap<>();
            colMap.put("b_factory_id",u.getUFactoryId());
            colMap.put("b_order_id",order.getOId());
            List<Bid> bidList =  bidMapper.selectByMap(colMap);
            if(bidList.get(0).getBState().equals("未中标")){
                orderVo.setState("未中标");
            }
            else if (order.getOState().equals("已发布")) {
                orderVo.setState("已投标");
            } else {
                orderVo.setState(order.getOState());
            }

            orderVo.setNum(order.getONum());
            orderVo.setReceiver_name(order.getOReceiverName());
            orderVo.setReceiver_tel(order.getOReceiverTel());
            orderVo.setReceiver_addr(order.getOReceiverAddr());
            orderVo.setDeliver_date(order.getODeliverDate());
            orderVo.setBid_end_date(order.getOBidEndDate());

            orderVo.setProduct_id(order.getOProductId());
            orderVo.setProduct_name(productMap.get(order.getOProductId()).getPName());

            orderVo.setUser_id(order.getOUserId());
            orderVo.setUser_true_name(userMap.get(order.getOUserId()).getUName());

            orderVoList.add(orderVo);
        }
        // 手动分页
        JSONObject result = new JSONObject();
        result.put("count", orderVoList.size());
        orderVoList = Utils.pageByMe(orderVoList, page, limit);
        result.put("data", orderVoList);
        return result;
    }

    public JSONObject listOrderSuAdmin(Integer page, Integer limit, String id, String receiver_name, String product_name) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        if (id != null && !id.isEmpty()) {
            queryWrapper.like("o_id", id);
        }
        if (receiver_name != null && !receiver_name.isEmpty()) {
            queryWrapper.like("o_receiver_name", receiver_name);
        }
        if (product_name != null && !product_name.isEmpty()) {
            queryWrapper.like("p_name", product_name);
        }
        List<Order> orderList = orderMapper.listJoinProduct(queryWrapper);

        List<Product> productList = productMapper.selectList(null);
        Map<Long, Product> productMap = new HashMap<>();
        productList.forEach(product -> {
            productMap.put(product.getPId(), product);
        });

        List<User> userList = userMapper.selectList(null);
        Map<Long, User> userMap = new HashMap<>();
        userList.forEach(user -> {
            userMap.put(user.getUId(), user);
        });

        List<OrderVo> orderVoList = new ArrayList<>();
        for (int i = 0; i < orderList.size(); i++) {
            Order order = orderList.get(i);
            OrderVo orderVo = new OrderVo();
            orderVo.setId(order.getOId());
            orderVo.setState(order.getOState());
            orderVo.setNum(order.getONum());
            orderVo.setReceiver_name(order.getOReceiverName());
            orderVo.setReceiver_tel(order.getOReceiverTel());
            orderVo.setReceiver_addr(order.getOReceiverAddr());
            orderVo.setDeliver_date(order.getODeliverDate());
            orderVo.setBid_end_date(order.getOBidEndDate());

            orderVo.setProduct_id(order.getOProductId());
            orderVo.setProduct_name(productMap.get(order.getOProductId()).getPName());

            orderVo.setUser_id(order.getOUserId());
            orderVo.setUser_true_name(userMap.get(order.getOUserId()).getUName());

            orderVoList.add(orderVo);
        }
        // 手动分页
        JSONObject result = new JSONObject();
        result.put("count", orderVoList.size());
        orderVoList = Utils.pageByMe(orderVoList, page, limit);
        result.put("data", orderVoList);
        return result;
    }
}
